## 装饰器使用场景举例
### 计算函数执行时间
import time
from functools import wraps

def time_it(func):
    @wraps(func)
    def wrapper(*args,**kwargs):
        start = time.time()
        result = func(*args,**kwargs)
        end = time.time()
        print(f"{func.__name__} executed in {end - start} seconds")
        return result
    return wrapper

@time_it
def calculate01(n):
    return sum(range(n))

print(calculate01(553434))


### web权限控制

def admin_required(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        if not is_admin():
            return "You are not authorized to access this page"
        return func(*args, **kwargs)
    return wrapper

@admin_required
def admin_page():
    return "Welcome to admin page"

def is_admin():
    # 模拟判断用户是否是管理员
    return True
    # return False

print(admin_page())

### log：函数各时刻的输入输出
def logging(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        print(f"Calling {func.__name__} with args:{args} and kwargs{kwargs}")
        result = func(*args, **kwargs)
        print(f"Function {func.__name__} result returned {result}")
        return result
    return wrapper

@logging
def add(x,y):
    return x + y

print(add(3,3))

